package com.tangsm.spring.boot.validation.domain.vo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tangsm.spring.boot.validation.enums.ResultStatus;

import java.io.Serializable;

/**
 * 自定义统一响应体
 *
 * @param <T> 数据对象
 */
public class Result<T> implements Serializable {
    /**
     * 状态码
     */
    private final String code;

    /**
     * 描述信息
     */
    private final String msg;

    /**
     * 响应的具体数据
     */
    private final T data;

    /**
     * 自定义响应数据的私有构造
     *
     * @param resultStatus 响应码枚举
     * @param data         数据对象
     */
    private Result(ResultStatus resultStatus, T data, String msg) {
        this.code = resultStatus.getCode();
        if (msg == null || "".equals(msg)) {
            this.msg = resultStatus.getMsg();
        } else {
            this.msg = msg;
        }
        this.data = data;
    }

    /**
     * 业务成功
     */
    public static <T> Result<T> success() {
        return new Result<>(ResultStatus.SUCCESS, null, null);
    }

    /**
     * 业务成功，返回响应数据
     *
     * @param data 数据对象
     */
    public static <T> Result<T> success(T data) {
        return new Result<T>(ResultStatus.SUCCESS, data, null);
    }

    /**
     * 业务失败
     */
    public static <T> Result<T> failure() {
        return new Result<>(ResultStatus.FAILURE, null, null);
    }

    /**
     * 业务失败，返回自定义描述信息
     */
    public static <T> Result<T> failure(String msg) {
        return new Result<>(ResultStatus.FAILURE, null, msg);
    }

    /**
     * 业务失败，返回响应数据
     */
    public static <T> Result<T> failure(T data) {
        return new Result<>(ResultStatus.FAILURE, data, null);
    }

    /**
     * 业务失败，返回响应码枚举信息
     */
    public static <T> Result<T> failure(ResultStatus resultStatus) {
        return failure(resultStatus, null);
    }

    /**
     * 业务失败，返回响应码枚举信息和响应数据
     */
    public static <T> Result<T> failure(ResultStatus resultStatus, T data) {
        if (resultStatus == null) {
            return new Result<>(ResultStatus.FAILURE, null, null);
        }
        return new Result<>(resultStatus, data, null);
    }

    /**
     * 参数验证异常，返回自定义描述信息
     */
    public static <T> Result<T> verifyError(String msg) {
        return new Result<>(ResultStatus.PARAM_FAILED, null, msg);
    }

    public String getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public T getData() {
        return data;
    }

    @Override
    public String toString() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return "Result{" +
                    "code='" + code + '\'' +
                    ", msg='" + msg + '\'' +
                    ", data=" + objectMapper.writeValueAsString(data) +
                    '}';
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
